import { Component, OnInit, ViewEncapsulation, Injector } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { EstimatedCostServiceProxy, EstimatedWorkshopCostDto } from '@shared/service-proxies/service-proxies';
import * as _ from 'lodash';

@Component({
    templateUrl: './workshop.component.html',
    styleUrls: ['./workshop.componen.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class RealtimeCostWorkshopComponent extends AppComponentBase implements OnInit {
    tableData = Array<EstimatedWorkshopCostDto>();

    categories = ['原材料', '辅材', '标准件', '工装', '外协费', '其他直接成本', '燃动', '人工', '制造费'];
    workshops = new Array();

    chartCosts = new Array();

    selectedDate = new Date();
    constructor(injector: Injector, private _costService: EstimatedCostServiceProxy) {
        super(injector);
    }

    ngOnInit(): void {
        this.workshops = _.filter(
            this.getWorkshops(),
            e => e.value.toString() !== '4001' && e.value.toString() !== '4002'
        );
        this.getData();
    }

    getData() {
        this._costService
            .getWorkshopEstimatedCosts(this.selectedDate.getFullYear(), this.selectedDate.getMonth() + 1)
            .subscribe(result => {
                this.tableData = result.items;
                this.initChart();
            });
    }

    getCellDate(row: string, col: string) {
        let cost = _.find(this.tableData, e => e.workshop === row.toString() && e.category === col);
        return cost ? cost.amount : 0;
    }

    initChart() {
        let data = _.filter(this.tableData, e => e.workshop !== '4001' && e.workshop !== '4002');

        let result = _.groupBy(data, e => e.workshop);

        let chartCosts = _.map(result, (v, k) => ({
            name: k,
            series: _.map(v, e => ({ name: e.category, value: e.amount }))
        }));

        _.each(chartCosts, e => {
            let series = [];

            _.each(this.categories, c => {
                let serie = _.find(e.series, e => e.name === c);

                if (serie) {
                    series.push({
                        name: c,
                        value: serie.value
                    });
                } else {
                    series.push({
                        name: c,
                        value: 0
                    });
                }
            });

            e.series = series;
        });

        this.chartCosts = chartCosts;
    }
}
